package com.ruoyi.project.tool.swagger.UserController;


import okhttp3.HttpUrl;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.UUID;

public class SignUtil {

    // Authorization:
// GET - getToken("GET", httpurl, "")
// POST - getToken("POST", httpurl, json)
    String schema = "WECHATPAY2-SHA256-RSA2048";
//    HttpUrl httpurl = HttpUrl.parse(url);

    public String getToken(String method, HttpUrl url, String body) throws Exception {
        String nonceStr = UUID.randomUUID().toString();
        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage(method, url, timestamp, nonceStr, body);
        String signature = sign(message.getBytes("utf-8"));
        String yourCertificateSerialNo = "134FDBB0C6E680BAAE9979AC0E2E66F8C445572D";
        String yourMerchantId = "1605617216";
        return "mchid=\"" + yourMerchantId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + yourCertificateSerialNo + "\","
                + "signature=\"" + signature + "\"";
    }

    String sign(byte[] message) throws NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, IOException, InvalidKeyException {
        Signature sign = Signature.getInstance("SHA256withRSA");
//        sign.initSign(getPrivateKey("E:\\RuoYi-Theme\\ruoyi\\src\\main\\resources\\apiclient_key.pem"));
        String content = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDOAYMvCHTgZbcS\n" +
                "sg1fJ3IOZBBVVHyoA9nX/3dWofSTqUDi7D1D/WQ647eVzZbHYc10/FVT9XByCTgo\n" +
                "8lQc+Eco00cWSGYLQpaCV0jF9igFSq8C5rZOEJ+4wIUWnV4rSp5ijGfyWM0Unzl+\n" +
                "jcVBvmMC/aqXkTv5cA7k6slknaFfG3KoqacjdeeWaAqK2aY7blBIIjjseg0VwOGT\n" +
                "SdByWBkaUUUHjlOX0P7nTl6k1sqv9iIXHNkiAdUBuXujkYMoUPQcjiExlF+ftMFd\n" +
                "NzXNMI1d5ShbtV/od2WJbKvuL78/vmhsn1RtmkPRIEJkqEM0ylMBTGs69qpR43Rn\n" +
                "4TPYlnCjAgMBAAECggEAQyhhENMr7v+Z2CFtlIiyeRiL7pV1cfyXZwAkcnyn0/+I\n" +
                "ZLHpIyIXK8+SyOZV8jfjF/EvDAjmmHaC9W5Sl4MlB50g/pWplqAlmuZDli2yTE9V\n" +
                "kJeP9REcUMmKWZ4B1hEkYzIsrOfgK4ng323uUYl0k8QIehLhv2aVpHEaKI/uzKb7\n" +
                "ORxhuWw2IFHuqhwfuVk6GqoRgJxux8sZpnIVv0dmCRNuJf4HHBPYYMdvEUac4FMB\n" +
                "YhShW87owT7ZqKtbDbLxNSFxg+lixwjUUuJT4hvKaQ7wZ5E21/7YC61TTC8Z8Zy8\n" +
                "drbH0VK9xFc7vul30pQijA4LQgJm6qDCEb0p3OECaQKBgQDut5nPrLi8zha7OSyM\n" +
                "iX9Rx61i2IY6wzMzYmwwgRRQVFWKfZ3NG8ZUe8dis4e6/mmc3vv1p8GCPYOhkzlc\n" +
                "H0G1JqVbevPMumOaEKB/CtNGPW0b+gXVnmAA6998ZfDJu+421KAIDkXbGE74CqiB\n" +
                "hciKns1HlnZ+TSoaVOtfrUJtPwKBgQDc66OAHablyFQynwMNAA7luU9XhpAmGXKY\n" +
                "ZpK7zwekSzhO3JEZBpew3vdX3JVb7+fgVLrXwPFwCYIblp3qj3zxuOyJ+lDiQsuC\n" +
                "929wYelU65Ay7y0e8DFMTyvg3/aDVv3bZnjKptU3f36fxWGO/5BbjEul3VkuxiUT\n" +
                "WV1uiR1PnQKBgQCLomvfNZouHqLfSxdK8Za/AHzkZ+FEeC/366d7S9XVEy+iPc5T\n" +
                "Tt7ZRjof+wH3GKAweaKKVGF1zIO1vId94m6uBvgMpcP8Sj6+vOEUzwE8gevTxJEr\n" +
                "HmPrxg1JF9wcNMin3AHsFGU6PmLa5mkgsl/W7gMHz/Rp9rsdAfVYVuGXQwKBgEkS\n" +
                "U9EzfZmxalAYEl1BcKwBYEH2C0Xe0u2ft9cRAlkQXD6RbBjX+mKRTUStfGWdc5fa\n" +
                "zrZAZluFeZiAeBk2fsBBR1PYDNrZ9xCJoT2N1Sy2gcqnG8iI7/VqlnvZ+GK26l6g\n" +
                "hUGabxndPNfB5KP02h29yOPC1BXJikfdHi9KgPxtAoGBANBY1EhVG/Fg2sEIxG2s\n" +
                "KmGeKiHHmSWU19PbAnYsKu09EFvr4c9YbisWip/m7YAx8Ahgdo1RcieDJipWKwZp\n" +
                "4OVOCbdf8WE4KKYEh6o0CcjpSaM/P4Qc6BcIZUtzsYUlNMXwhwUuDTzEvq9a+hUf\n" +
                "h2QSTyXtVF1r/GKvMZA8izTk";
                sign.initSign(getPrivateKey(content));
                sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    /**
     * 获取私钥。
     *
     * @param content 私钥文件路径  (required)
     * @return 私钥对象
     */
    public static PrivateKey getPrivateKey(String content) throws IOException {
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }


    String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }
}
